/**
 * Creat with IntelliJ IDEA
 * Description:不同线程的run()方法中的局部变量互不干扰
 * User:WZW
 * Date:2021-11-26
 * Time:21:21
 */

class Move implements Runnable
{
    String s1,s2;
    Move(String s1,String s2){
        this.s1=s1;
        this.s2=s2;
    }
    public void run(){
        int i=0;//局部变量
        while(true){
            if(Thread.currentThread().getName().equals(s1)){//当线程s1占用CPU资源时
                i=i+1;
                System.out.println(s1 + ":" + i);
                if(i>=4){
                    System.out.println(s1 + "Finished");
                    return;
                }
            }
            else if(Thread.currentThread().getName().equals(s2)){//当线程s2占用CPU资源时
                i=i-1;
                System.out.println(s2 + ":" + i);
                if(i<=-4){
                    System.out.println(s2 + "Finished");
                    return;
                }
            }
            try{ Thread.sleep(800); }//中断0.8秒
            catch(InterruptedException e) {}
        }
    }
}

public class Example8_6 {
    public static void main(String args[])
    {
        String s1 = "ZHANG San";
        String s2 = "LI Si";
        Move move = new Move(s1,s2);

        Thread zhang, li;
        zhang = new Thread(move); // 目标对象move
        li = new Thread(move); // 目标对象move
        zhang.setName(s1);
        li.setName(s2);
        zhang.start();
        li.start();
    }

}
